package org.example.utils

import org.example.dao.HighRiskRoad

/**
 * 点工具类
 */
object PointUtil {
  val a = 6378245.0 //克拉索夫斯基椭球参数长半轴a
  val L = 6381372 * Math.PI * 2 //地球周长

  /**
   * 判断一组点是否由点在某段路上
   *
   * @param highRiskLocation
   * @param polyCurve
   * @return
   */
  def isInPolyCurve(highRiskLocation: IndexedSeq[HighRiskRoad], polyCurve: Array[(Double, Double)]): Boolean = {
    var flag = false
    for (i <- 0 until polyCurve.length - 1 if !flag) {
      val firstLocation = polyCurve(i)
      val secondLocation = polyCurve(i + 1)
      val distance = CommonUtils.getDistance(firstLocation._2, firstLocation._1, secondLocation._2, secondLocation._1)
      highRiskLocation.foreach { location =>
        val distanceA = CommonUtils.getDistance(location.lat.toDouble, location.lon.toDouble, firstLocation._2, firstLocation._1)
        val distanceB = CommonUtils.getDistance(location.lat.toDouble, location.lon.toDouble, secondLocation._2, secondLocation._1)
        if (distanceA <= distance && distanceB <= distance) {
          flag = true
        }
      }
    }

    flag
  }

  /**
   * 将经纬度转换为平面坐标系
   *
   * @param lon
   * @param lat
   * @return
   */
  def coordinateTransform(lon: Double, lat: Double): (Double, Double) = {
    // 平面展开后，x轴等于周长
    val W = L
    // y轴约等于周长一半
    val H = L / 2
    // 米勒投影中的一个常数，范围大约在正负2.3之间
    val mill = 2.3
    // 将经度从度数转换为弧度
    var x = lon * Math.PI / 180
    // 将纬度从度数转换为弧度
    var y = lat * Math.PI / 180
    // 米勒投影的转换
    y = 1.25 * Math.log(Math.tan(0.25 * Math.PI + 0.4 * y))

    // 弧度转为实际距离
    x = (W / 2) + (W / (2 * Math.PI)) * x
    y = (H / 2) - (H / (2 * mill)) * y
    (x, y)
  }
}
